<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :pagination="pagination"
      :rule-form="ruleForms"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @resetForm="resetForm"
    >

      <!--        课程分页-->
      <template slot="selectMajor" >
        <el-form-item label="专业名称">
          <el-select  @clear="classClear" :remote-method="classFilterMethod" remote filterable
                      v-model="ruleForms['major_id']['major_id']"
                      clearable placeholder="请选择">
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[0]['options']"
              :key="item.id"
              :label="item.title + ' => ' + item.level "
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="classCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.majorPage.currentPage"
              :total="pageSizes.majorPage.total">
            </el-pagination>
          </el-select>
        </el-form-item>
      </template>
      <!--        end-->

    </x-Table>
    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >
        <!--        课程分页-->
        <template slot="type-page-select-major" >
          <el-select  @clear="classClear" :remote-method="classFilterMethod" remote filterable
                     v-model="rule[0].value"
                     clearable placeholder="请选择">
            <el-option
              style='width: 260px;text-align: center'
              v-for="item in rule[0]['options']"
              :key="item.id"
              :label="item.title + ' => ' + item.level "
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="classCurrentChange"
              small
              layout="prev, pager, next"
              :page-size="20"
              :current-page="pageSizes.majorPage.currentPage"
              :total="pageSizes.majorPage.total">
            </el-pagination>
          </el-select>
        </template>
        <!--        end-->
      </form-create>
    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
let _this;
export default {
  data() {
    return {
      loading: true,
      row: null, //当前选择数据
      ruleForms: {
        major_id: {label: "专业名称", prop: "major_id", type: "slot",slot:'selectMajor',major_id:''},
        class_code: {label: "课程代码", prop: "class_code", type: "text"},
        title: {label: "课程名称", prop: "title", type: "text"},
        garde: {label: "入学批次", prop: "garde", type: "text"},
        class_type: {label: "课程类别", prop: "class_type", type: "text"},
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      otherParam: {
        halfCheckedKeys: [],
      }, //如果有其他情况会拼接这个参数
      fapi: {},
      pageSizes: {
        majorPage: {
          currentPage: 1,
          total: 0,
        },
      },
      formParam: {},
      rule: [
        {
          "type": "pageSelectMajor",
          "field": "major_id",
          "title": "专业名称",
          "info": "",
          "options": [],
          "hidden": false,
          "display": true,
          "value": '',
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择课程",
              "required": true,
              "type": "number"
            }
          ]
        },
        {
          "type": "upload",
          "field": "class_img",
          "title": "封面图",
          "info": "",
          "props": {
            "action": "http://www.free.com/api/Upload/upload",
            "onSuccess": function (res,file){
              file.url = res.data[0].url;
            },
            "uploadType":'image',
            'name':'file',
            limit:1
          },
          "_fc_drag_tag": "upload",
          "hidden": false,
          "display": true,
          "value":[]
        },
        {
          "type": "input",
          "field": "class_code",
          "title": "课程代码",
          "info": "",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true
        },
        {
          "type": "input",
          "field": "garde",
          "title": "入学批次",
          "props": {
            "type": "number"
          },
          "info": "入学批次为年份(比如2022年就填写2022)",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true,
          "validate": [
            {
              "type": "string",
              "trigger": "change",
              "mode": "required",
              "message": "请输入学批次",
              "required": true
            }
          ]
        },
        {
          "type": "input",
          "field": "title",
          "title": "课程名称",
          "info": "",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true,
          "validate": [
            {
              "type": "string",
              "trigger": "change",
              "mode": "required",
              "message": "请输入课程名称",
              "required": true
            }
          ]
        },
        {
          "type": "input",
          "field": "class_type",
          "title": "课程类型",
          "info": "必修,选修,具体看教务安排",
          "_fc_drag_tag": "input",
          "hidden": false,
          "display": true
        },
        {
          "type": "switch",
          "field": "is_drat",
          "title": "开启拖拽",
          "info": "",
          "_fc_drag_tag": "switch",
          "hidden": false,
          "display": true
        },
        {
          "type": "switch",
          "field": "is_speed",
          "title": "开启倍速",
          "info": "",
          "_fc_drag_tag": "switch",
          "hidden": false,
          "display": true
        },
        {
          "type": "slider",
          "field": "progress",
          "title": "播放进度",
          "info": "视频播放到设置进度算完成",
          "_fc_drag_tag": "slider",
          "hidden": false,
          "display": true,
          "value": 90
        },
        {
          "type": "inputNumber",
          "field": "score",
          "title": "学分",
          "info": "",
          "props": {
            "min": 1
          },
          "_fc_drag_tag": "inputNumber",
          "hidden": false,
          "display": true
        },
        {
          "type": "datePicker",
          "field": "start_time",
          "title": "开课时间",
          "info": "",
          "props": {
            "type": "datetime"
          },
          "_fc_drag_tag": "datePicker",
          "hidden": false,
          "display": true,
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择开课时间",
              "required": true,
              "type": "string"
            }
          ]
        },
        {
          "type": "datePicker",
          "field": "end_time",
          "title": "结课时间",
          "info": "",
          "props": {
            "type": "datetime"
          },
          "_fc_drag_tag": "datePicker",
          "hidden": false,
          "display": true,
          "validate": [
            {
              "trigger": "change",
              "mode": "required",
              "message": "请选择结课时间",
              "required": true,
              "type": "string"
            }
          ]
        }
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          major_id: {label: "专业名称", prop: "major_id",type:'two',options:{obj:'majors',objKey:'title'}},
          class_code: {label: "课程代码", prop: "class_code"},
          class_img: {
            label: '课程封面图',
            prop: 'class_img',
            type: 'image',
            sing:',',
            style: { width: '30px', height: '30px' },
            preview: function(scope,item,index) {
              console.log(scope)
              console.log(item)
              console.log(index)
            },
          },
          title: {label: "课程名称", prop: "title"},
          is_speed: {
            label: "倍速播放",
            prop: "is_speed",
            type: "switch",
            activeValue: true,
            inactiveValue: false,
            switchChage: function (scope) {
              console.log(scope)
            },
          },
          is_drat: {
            label: "是否拖拽",
            prop: "is_drat",
            type: "switch",
            activeValue: true,
            inactiveValue: false,
            switchChage: function (scope) {
              console.log(scope)
            },
          },
          progress: {label: "播放进度", prop: "progress", type: 'progress'},
          class_type: {label: "课程类别", prop: "class_type"},
          score: {label: "学分", prop: "score", type: 'tag'},
          garde: {label: "入学批次", prop: "garde"},
          start_time: {label: "开课时间", prop: "start_time", order: true},
          end_time: {label: "结课时间", prop: "end_time", order: true},
          create_time: {label: "创建时间", prop: "create_time"},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              setTimeout(() => {
                _this.fapi.setValue("major_id", scope["row"].major_id);
                _this.fapi.setValue("class_code", scope["row"].class_code);
                _this.fapi.setValue("garde", scope["row"]['garde']);
                _this.fapi.setValue("title", scope["row"]['title']);
                _this.fapi.setValue("is_drat", scope["row"]['is_drat']);
                _this.fapi.setValue("class_img", scope["row"]['class_img']);
                _this.fapi.setValue("is_speed", scope["row"]['is_speed']);
                _this.fapi.setValue("progress", scope["row"]['progress']);
                _this.fapi.setValue("class_type", scope["row"]['class_type']);
                _this.fapi.setValue("score", scope["row"]['score']);
                _this.fapi.setValue("start_time", scope["row"]['start_time']);
                _this.fapi.setValue("end_time", scope["row"]['end_time']);
              }, 0);
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
            },
            del: function (scope) {
              _this.deleteDate(scope["row"].id);
            },
          },
        },
      },
    };
  },
  methods: {

    resetForm:function (){
      _this.searchParams = {};
    },


    classCurrentChange:function (val){
      _this.getMajorList(val);
    },

    classClear: function () {
      _this.getMajorList();
    },
    classFilterMethod: function (val) {
      _this.getMajorList(1,val)
    },

    handlePaginationCurrentChange: function (val) {
      _this.loading = true;
      _this.pagination["currentPage"] = val;
      _this.getDateList(_this.searchParams);
    },

    handlePaginationSizeChange: function (val) {
      _this.loading = true;
      _this.pagination["pageSize"] = val;
      _this.getDateList(_this.searchParams);
    },

    /**
     * 查询所有数据
     */
    getDateList: function (val) {
      _this.$store
        .dispatch("office/getClassList", val ? {
          major_id:val['major_id'],
          class_code:val['class_code'],
          garde:val['garde'],
          title:val['title'],
          class_type:val['class_type'],
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        } : {})
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.office.classList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },

    /**
     * 查询专业数据
     */
    getMajorList: function (page = 1, title) {
      _this.$store
        .dispatch("office/searchMajorList", {
          page: page,
          title: title
        })
        .then(() => {
          _this.rule[0].options = [];
          _this.rule[0].options = this.$store.state.office.majorList.data;
          _this.pageSizes.majorPage.total = this.$store.state.office.majorList.total;
          _this.pageSizes.majorPage.currentPage = this.$store.state.office.majorList.current_page;
        });
    },


    /**
     * 批量删除
     */
    handleHeardDel: function (val) {
      let del = [];
      val.forEach((item, index) => {
        del.push(item.id);
      });
      _this.deleteDate(del);
    },


    addDate: function (param) {
      _this.$store
        .dispatch("office/addClass", {
          major_id: param["major_id"],
          class_code: param["class_code"],
          garde: param["garde"],
          title: param["title"],
          class_img:param['class_img'],
          is_drat: param["is_drat"],
          is_speed: param["is_speed"],
          progress: param["progress"],
          class_type: param["class_type"],
          score: param["score"],
          start_time: param["start_time"],
          end_time: param["end_time"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.$message.success(msg);
            _this.getDateList();
          } else {
            _this.$message.error(msg);
          }
        });
    },
    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      if (_this.alertTitle === "添加") {
        _this.addDate(val);
      } else {
        //编辑
        _this.updateDate(val);
      }
    },

    /**
     * 搜索
     */
    searchForm: function (val) {
      _this.searchParams = val;
      _this.loading  = true;
      _this.getDateList(val);
    },
    /**
     * 更新数据
     */
    updateDate: function (param) {
      _this.$store
        .dispatch("office/updateClass", {
          id: _this.row["id"],
          major_id: param["major_id"],
          class_code: param["class_code"],
          garde: param["garde"],
          title: param["title"],
          is_drat: param["is_drat"],
          class_img:param['class_img'],
          is_speed: param["is_speed"],
          progress: param["progress"],
          class_type: param["class_type"],
          score: param["score"],
          start_time: param["start_time"],
          end_time: param["end_time"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     * 删除
     */
    deleteDate: function (val) {
      _this.$store
        .dispatch("office/delClass", {
          id: val,
        })
        .then((res) => {
          const {data, msg} = res;
          if (data) {
            _this.getDateList();
            _this.$message.success(msg);
            return;
          }
          return _this.$message.error(msg);
        });
    },

    /**
     *  表单导航栏添加点击
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      this.dialogVisible = true;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
          _this.fapi.setValue('content', '');
        }
      }, 0);
    },
  },
  created() {
    _this = this;
  },
  mounted() {
    this.getDateList();
    this.getMajorList();
  },
};
</script>

<style scoped></style>
